<template>
  <div>
    <a-row :gutter="12">
      <a-col :md="4" :sm="24" :lg="4">
        <a-card
          :bordered="false"
          :loading="treeLoading"
          :bodyStyle="{ padding: '0px 10px' }"
          style="overflow: auto; min-height: 390px"
        >
          <div v-if="this.treeData != ''">
            <a-tree
              :treeData="treeData"
              v-if="treeData.length"
              @select="handleClick($event,'one')"
              :defaultExpandAll="false"
              :replace-fields="replaceFields"
              :defaultExpandedKeys="defaultExpandedKeys"
            >
              <template #title="{ key: treeKey, name }">
                <a-dropdown :trigger="['contextmenu']">
                  <span>{{ name }}</span>
                  <template #overlay>
                    <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                      <a-menu-item key="1" @click="editClass"><a-icon type="edit" />编辑</a-menu-item>
                      <a-menu-item key="2" @click="deleteClass"><a-icon type="delete" />删除</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
          </div>
          <div v-else>
            <a-empty :image="simpleImage" />
          </div>
        </a-card>
      </a-col>
      <a-col :md="20" :sm="24" :lg="20">
        <x-card v-if="hasPerm('sysUser:page')">
          <div slot="content" class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <!-- <a-col :md="6" :sm="24">
                  <a-form-item label="项目编码">
                    <a-input v-model.trim="queryParam.code" allow-clear placeholder="请输入项目编码" /> 
                  </a-form-item>
                </a-col> -->
                


                <a-col :md="5" :sm="24" class="number-input-box" style="padding-right:0;">
                  <a-form-item label="名称">
                    <a-input v-model.trim="queryParam.name" allow-clear placeholder="项目名称/拼音码" @keydown.enter="search"></a-input>
                    <!-- <a-input v-model="queryParam.searchValue" allow-clear placeholder="请输入项目名称" /> -->
                  </a-form-item>
                </a-col>
                <!-- <a-col :md="6" :sm="24">
                  <a-form-item label="拼音码">
                    <a-input v-model.trim="queryParam.pyCode" allow-clear placeholder="请输入拼音码" />
                     
                  </a-form-item>
                </a-col> -->


                <a-col :md="5" :sm="24" >
                  <a-form-item label="启用状态">
                    <!-- <a-switch @change="isDisabledChange" />  -->
                    <a-select 
                      @change="isDisabledChange" 
                      placeholder="请选择"
                      allowClear
                      v-model="queryParam.isDisabled"
                    >
                      <a-select-option :value="undefined">
                        <div>请选择</div>
                      </a-select-option>
                      <a-select-option :value="0">
                        <div>已启用</div>
                      </a-select-option>
                      <a-select-option :value="1">
                        <div>未启用</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                  
                </a-col>
                <a-col :md="5" :sm="24" style="padding-right:0;padding-left:0">
                  <a-form-item label="核算业绩">
                    <!-- <a-switch @change="isCalculateChange" />  -->
                    <a-select 
                      @change="isCalculateChange" 
                      placeholder="请选择"
                      allowClear
                      v-model="queryParam.isAchieve"
                    >
                      <a-select-option :value="undefined">
                        <div>请选择</div>
                      </a-select-option>
                      <a-select-option :value="0">
                        <div>否</div>
                      </a-select-option>
                      <a-select-option :value="1">
                        <div>是</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                




                <a-col :md="6" :sm="24" style="padding-right:0;">
                  <!-- <a-button type="primary" @click="$refs.table.refresh(true)">1查询</a-button>  this.$refs.table.refresh只是一个刷新方法-->
                  <a-button type="primary" @click="search('one')">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </a-col>
                
              </a-row>
              <a-row :gutter="48">
                <a-col :md="6" :sm="24" style="padding-right:0;">
                  <a-form-item label="耗材名称">
                    <a-input v-model.trim="queryParam.consumableName" allow-clear placeholder="请输入耗材名称" @keydown.enter="search"></a-input> 
                  </a-form-item>
                </a-col>

                <a-col :md="9" :sm="24" style="padding-right:0;">
                  <a-form-item label="价格区间">
                   
                    <a-input-number
                      :min="1" 
                      :default-value="0"
                      :value="queryParam.minPrice"
                      :formatter="value => `${value}`"
                      :parser="value => value.replace(/\$\s?|(,*)/g, '')"  
                      @change="value => {  
                        if(!isNumber(value)){
                          this.queryParam.minPrice = undefined
                        }else{
                          this.queryParam.minPrice = Number(value)
                          this.queryParam = Object.assign({},this.queryParam)
                        } 
                      }" 
                      
                    />
                    -
                    <a-input-number
                      :default-value="0"
                      :value="queryParam.maxPrice"
                      :min="queryParam.minPrice" 
                      :formatter="value => `${value}`"
                      :parser="value => value.replace('%', '')" 
                      @change="value => {  
                        if(!isNumber(value)){
                          this.queryParam.maxPrice = undefined
                        }else{
                          this.queryParam.maxPrice = Number(value)
                          this.queryParam = Object.assign({},this.queryParam)
                        } 
                      }" 
                    />
                     
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </x-card>
        <!-- <a-modal :visible="visibleS" title="项目编码更新" @ok="handleOks" @cancel="handleCancels">
          <a-form>
            <a-form-item label="项目类别">
              <a-input></a-input>
            </a-form-item>
            <a-form-item label="编码前缀">
              <a-input></a-input>
            </a-form-item>
            <a-form-item>
              <div>
                <a-button type="primary">取消</a-button>
                <a-button type="primary">更新</a-button>
                <a-bnutton type="primary">刷新</a-bnutton>
              </div>

            </a-form-item>
          </a-form>
        </a-modal> -->
        <a-card :bordered="false">
          <div style="position: absolute; top: 10px; left: 24px">
            <!-- <a-button icon="plus-circle" type="primary" @click="addClass">新增类别</a-button> -->
            <a-button icon="plus-circle" type="primary" @click="addProject">新增</a-button>
            <!-- <a-button icon="plus-circle" type="primary" @click="updateCode">批量更新编码</a-button>
            <a-button icon="plus-circle" type="primary">导出</a-button>
            <a-button icon="plus-circle" type="primary">启用</a-button>
            <a-button icon="plus-circle" type="primary">禁用</a-button> -->
          </div>
          <super-table
            ls_props_columns="projectManage_table"
            :scroll="{ x: 1000 }"
            ref="table"
            :pageSize="20"
            :columns="columns"
            :data="loadData"
            :rowKey="(record) => record.id"  
          >
            <template slot="isAchieve" slot-scope="tags">
              <a-tag :color="tags==true || tags == '1' ? 'red' : 'green' ">
                {{ tags==true || tags == '1'?'是':'否' }}
              </a-tag>
            </template>
            <template slot="isDisabled" slot-scope="tags">
              <a-tag :color="tags==true || tags == '1' ? '#d9d9d9' : '#39f' ">
                {{ tags==true || tags == '1'?'未启用':'已启用' }}
              </a-tag>
            </template>
            <!--名称-->
            <template slot="name" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--打印名称-->
            <template slot="printName" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--手术名称-->
            <template slot="operateName" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--操作-->
            <template slot="action" slot-scope="text, record">
              <div class="g-flex g-y-center">
                <a-button type="link" @click="editProject(record)">修改</a-button>
              </div>
            </template>
          </super-table>
        </a-card>
      </a-col>
    </a-row>
    <add-project
      @search="search"
      ref="addProject"
      :modal_type="modal_type"
      :row_record="current_row_record"
    ></add-project>
    <add-class ref="addClass" :modal_type="modal_type" :row_record="current_row_record"></add-class>
  </div>
</template>
<script>
import { SuperTable, XCard, XDown } from '@/components'
import { Empty } from 'ant-design-vue'
import { sysUserChangeStatus, sysUserExport } from '@/api/modular/system/userManage'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
import { getItemClasssify, getItemDetailById } from '@/api/modular/main/customer/customerScene'
import { Search } from '@/api/bd/pm'
import addProject from '@/views/baseData/projectManage/addProject'
import addClass from '@/views/baseData/projectManage/addClass'
export default {
  components: {
    XDown,
    XCard,
    SuperTable,
    addProject,
    addClass,
  },
  data() {
    return {
      visibleS: false,
      modal_type: 'add',
      current_row_record: {},
      // 查询参数
      // 查询参数
      queryParam: {
        code: '',
        name: '',
        // searchValue: '',
        pageNum: 1, //第几页
        pageSize: 10, //每页中显示数据的条数
        id: undefined,

        consumableName:'', // 耗材
        minPrice: undefined, // 价格区间
        maxPrice: undefined, // 价格区间
        isDisabled: undefined, // 是否禁用
        isAchieve: undefined, // 是否核算业绩

      },
      pagination: {
        current: 1, //当前页
        pageSize: 20, //当前页数
        total: 0, //总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'], //这里注意只能是字符串，不能是数字
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      // 表头
      columns: [
        {
          title: '核算业绩',
          align: 'center',
          dataIndex: 'isAchieve',
          width: 100,
          // customRender: (isAchieve) => {
          //   return isAchieve === '1' ? '是' : '否'
          // },
          scopedSlots: { customRender: 'isAchieve' },
        },
        {
          title: '启用状态',
          align: 'center',
          dataIndex: 'isDisabled',
          width: 100,
          // customRender: (isDisabled) => {
          //   return isDisabled === '1' ? '是' : '否'
          // },
          scopedSlots: { customRender: 'isDisabled' },
        },
        
        { title: '项目编码', align: 'center', dataIndex: 'code', width: 120, ellipsis: true },
        { title: '项目名称', align: 'center', dataIndex: 'name', width: 200, scopedSlots: { customRender: 'name' }, ellipsis: true },
        { title: '拼音码', align: 'center', dataIndex: 'pyCode', width: 120 },
        { title: '一级类别', align: 'center', dataIndex: 'oneStepId', width: 120 },
        { title: '二级类别', align: 'center', dataIndex: 'twoStepId', width: 120 },
        { title: '三级类别', align: 'center', dataIndex: 'threeStepId', width: 120 }, 
        {
          title: '耗材名称',
          align: 'center',
          dataIndex: 'dictItemName',
          key: 'dictItemName',
          ellipsis: true,
          width: 120,
          scopedSlots: { customRender: 'name' },
          customRender: (dictItemName) => {
            if (!dictItemName || dictItemName.toString() === 'null') {
              return '-'
            } else {
              return dictItemName
            }
          },
        },
        
        { title: '耗材数量', align: 'center', width: 120, dataIndex: 'numberConsumable', key: 'numberConsumable', ellipsis: true },
        
        // {
        //   title: '核算成交',
        //   dataIndex: 'isAchieve',
        //   width: 100,
        //   customRender: (name) => {
        //     return name === '1' ? '是' : '否'
        //   },
        // },
        
        // {
        //   title: '是否需要执行',
        //   dataIndex: 'isExecute',
        //   width: 100,
        //   customRender: (isExecute) => {
        //     return isExecute === '1' ? '是' : '否'
        //   },
        // },
        
        { title: '次数', align: 'center', dataIndex: 'useTimes', width: 80 },
        {
          title: '项目售价',
          align: 'center',
          dataIndex: 'price',
          width: 100,
          customRender: (price) => {
            return price!=undefined && price!='' ? '¥' + price : '-'
          },
        },
        // { title: '项目单位', dataIndex: 'itemUnit', width: 100 },
        // { title: '项目售价', dataIndex: 'price', width: 100},
        // { title: '最低价', dataIndex: 'minPrice', width: 100},
        // { title: '最高价', dataIndex: 'maxPrice', width: 100 },
        // { title: '执行科室', dataIndex: 'achieveDept', width: 100 },
        // { title: '业绩科室', dataIndex: 'execDept', width: 100 },
        // { title: '二级业绩科室', dataIndex: 'twoDeptName', width: 100 },
        // { title: '项目说明', dataIndex: 'modifier', width: 100 },
        // {
        //   title: '打印名称',
        //   dataIndex: 'printName',
        //   width: 100,
        //   scopedSlots: { customRender: 'printName' },
        //   ellipsis: true,
        // },
        // {
        //   title: '手术名称',
        //   dataIndex: 'operateName',
        //   width: 100,
        //   scopedSlots: { customRender: 'operateName' },
        //   ellipsis: true,
        // },
        // { title: '费用类别', dataIndex: 'royaltyRate', width: 100 },
        // { title: '医生分值', dataIndex: 'doctorScore', width: 100 },
        // { title: '护士分值', dataIndex: 'nurseScore', width: 100 },
        // { title: '编辑时间', dataIndex: 'recordDate', width: 100 },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action',width: 80 }, fixed: 'right', width: 80 },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.queryParam.current = parameter.pageNum
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        console.log(this.queryParam, parameter)
        return getItemDetailById(Object.assign(this.queryParam)).then((res) => {
          return res
        })

      }, 

      tableData: [],
      treeData: [],
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      sexDictTypeDropDown: [],
      statusDictTypeDropDown: [],
      treeLoading: true,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        title: 'name',
        key: 'id',
      },
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        },
      },

      clickShowNav: false

    }
  },
  created() {
    getItemClasssify().then((res) => {
      this.treeLoading = false
      // console.log('666',res)
      this.treeData = res.data
    })
  },
  watch:{
     
    clickShowNav(){
      if(!this.clickShowNav){
        this.loadData = (parameter) => { 
          this.queryParam.current = parameter.pageNum
          this.queryParam.pageNum = parameter.pageNum
          this.queryParam.pageSize = parameter.pageSize
          return Search(Object.assign(this.queryParam, parameter)).then((res) => {  
            return res 
          })
        } 
      }else{
        this.loadData = (parameter) => { 
          this.queryParam = { 
            current: parameter.pageNum,
            pageNum: parameter.pageNum,
            pageSize: parameter.pageSize
          }  
          return getItemDetailById(Object.assign(this.queryParam, parameter)).then((res) => {  
            return res 
          })
        } 
      }
    }
    
     
   
  },
  methods: {
    isNumber(value) {         //验证是否为数字
      var patrn = /^(-)?\d+(\.\d+)?$/;
      if (patrn.exec(value) == null || value == "") {
          return false
      } else {
          return true
      }
    },
    // 查询条件的是否禁用
    isDisabledChange (value){
      console.log(value)
      this.queryParam.isDisabled = value
    },
    // 查询条件是否核算业绩
    isCalculateChange(value){
      this.queryParam.isAchieve = value
    },

    reset() { 
      this.queryParam.pyCode = ''
      this.queryParam.name = ''
      this.queryParam.code = ''
      this.queryParam.consumableName='' // 耗材
      this.queryParam.minPrice = undefined // 价格区间
      this.queryParam.maxPrice = undefined // 价格区间
      this.queryParam.isDisabled = undefined // 是否禁用
      this.queryParam.isAchieve = undefined // 是否核算业绩
      this.queryParam = Object.assign({},this.queryParam)

      // this.loadData = (parameter) => {
      //   return Search(Object.assign(this.queryParam, parameter)).then((res) => {
      //     console.log('右边表格', res, this.parameter, this.queryParam)
      //     return res
      //   })
      // }
      // this.$nextTick(() => { 
      //   this.$refs.table.refresh()
      // })
    },
    search() {  
      this.clickShowNav = false 
      this.loadData = (parameter) => { 
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        this.queryParam.current = parameter.current
         
        return Search(Object.assign(this.queryParam, parameter)).then(res => {
          return res 
        }) 
      }
      this.$nextTick(() => {  
        this.$refs.table.refresh(true)
      })
    },
    updateCode() {
      this.visibleS = true
    },
    handleOks() {
      this.visibleS = false
    },
    handleCancels() {
      this.visibleS = false
    },

    /**
     * 新增类别
     */
    addClass() {
      this.modal_type = 'add'
      this.$refs.addClass.add()
    },
    /**
     * 编辑类别
     */
    editClass() {
      this.modal_type = 'edit'
      this.$refs.addClass.add()
    },
    onContextMenuClick(treeKey, menuKey) {
      console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`)
    },
    /**
     * 删除类别
     */
    deleteClass() {
      console.log('删除')
    },
    /**
     * 新增项目
     */
    addProject() {
      this.modal_type = 'add'
      this.$refs.addProject.add()
    },
    /**
     * 编辑项目
     */
    editProject(record) {
      this.modal_type = 'edit'
      this.current_row_record = record
      this.$refs.addProject.add()
    },
    sexFilter(sex) {
      const values = this.sexDictTypeDropDown.filter((item) => item.code == sex)
      if (values.length > 0) {
        return values[0].value
      }
    },
    statusFilter(status) {
      const values = this.statusDictTypeDropDown.filter((item) => item.code == status)
      if (values.length > 0) {
        return values[0].value
      }
    },
    /**
     * 获取字典数据
     */
    sysDictTypeDropDown(text) {
      sysDictTypeDropDown({ code: 'sex' }).then((res) => {
        this.sexDictTypeDropDown = res.data
      })
      sysDictTypeDropDown({ code: 'common_status' }).then((res) => {
        this.statusDictTypeDropDown = res.data
      })
    },
    /**
     * 修改用户状态
     */
    editUserStatus(code, record) {
      // eslint-disable-next-line no-unused-vars
      const status = 0
      // eslint-disable-next-line eqeqeq
      if (code == 0) {
        this.status = 1
        // eslint-disable-next-line eqeqeq
      } else if (code == 1) {
        this.status = 0
      }
      sysUserChangeStatus({ id: record.id, status: this.status }).then((res) => {
        if (res.success) {
          this.$message.success('操作成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('操作失败：' + res.message)
        }
      })
    },

    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ id: record.id }]
      this.sysUserDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { id: d }
      })
      this.sysUserDelete(paramIds)
    },
    /**
     * 批量导出
     */
    batchExport() {
      sysUserExport().then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    /**
     * 点击左侧树形菜单查询列表
     */
    handleClick(e,num) { 
      if (e.length == 0) {
        return
      }
      
      this.clickShowNav = true
      this.loadData = (parameter) => {
        if(num == 'one'){
          this.queryParam = {
            id: e.toString(),
            pageNum: 1,
            pageSize: 20,
            current: 1
          }
        }else{ 
          this.queryParam = { 
            id: e.toString(),
            current: parameter.pageNum,
            pageNum: parameter.pageNum,
            pageSize: parameter.pageSize
          } 
        }  
        return getItemDetailById(Object.assign(this.queryParam, parameter)).then((res) => {  
          return res 
        })
      }
      
      this.$nextTick(() => {
        this.$refs.table.refresh(true)
      })
       
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
 
  },
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
/deep/ .ant-card-body {
  padding: 0;
}

.number-input-box{
  .ant-form-item-children{
    display:flex;
  }
}
</style>
